package com.limanyik.family.generator;


import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成器
 *
 * @Author yechunlin
 * @Date 2019/8/15
 */
public class GeneratorRun {

    /**
     * 包名
     */
    public static String PACK_NAME = "com.limanyik.family.common";

    /**
     * 表前缀
     */
    public static String TABLE_PREFIX = "";

    /**
     * 前缀,模块名
     */
    public static String MODULE_NAME = "";

    /**
     * xml文件模块名
     */
    public static String MODULE_NAME_MAPPER = "";

    /**
     * 需要生成的表名数组，如果为空或为null则生成此数据库下面所有的表
     */
    public static String[] TABLE_NAMES = {"family_bucket_info","r_user_fbi","relative_bucket_info","r_user_rbi"};

    /**
     * 数据库url
     */
    public static String DATABASE_URL = "jdbc:mysql://localhost:3306/family?useSSL=false";

    /**
     * 数据库账号
     */
    public static String DATABASE_USERNAME = "root";

    /**
     * 数据库密码
     */
    public static String DATABASE_PASSWORD = "123456";

    /**
     * 数据库驱动
     */
    public static String DATABASE_DRIVER = "com.mysql.jdbc.Driver";

    /**
     * @Author yechunlin
     * @Date 2019/8/15
     */
    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        final String projectPath = System.getProperty("user.dir");
        //final String projectPath = "E://code";
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("limanyi");
        gc.setServiceName("%sService");
        gc.setOpen(false);
        gc.setFileOverride(true);
        gc.setActiveRecord(true);
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML columList
        gc.setSwagger2(true); //实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(DATABASE_URL);
        dsc.setDriverName(DATABASE_DRIVER);
        dsc.setUsername(DATABASE_USERNAME);
        dsc.setPassword(DATABASE_PASSWORD);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        // pc.setModuleName(MODULE_NAME);
        pc.setParent(PACK_NAME);

        if (StringUtils.isNotBlank(MODULE_NAME)) {
            pc.setController("controller." + MODULE_NAME);
            pc.setService("service." + MODULE_NAME);
            pc.setServiceImpl("service.impl." + MODULE_NAME);
            pc.setMapper("mapper." + MODULE_NAME);
            pc.setEntity("entity." + MODULE_NAME);
        } else {
            pc.setController("controller");
            pc.setService("service");
            pc.setServiceImpl("service.impl");
            pc.setMapper("mapper");
            pc.setEntity("entity");
        }

        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("packName", PACK_NAME);
                this.setMap(map);
            }
        };

        String xmlTemplatePath = "/templates/mapper.xml.ftl";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();

        focList.add(new FileOutConfig(xmlTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/src/main/resources/mapper/" + MODULE_NAME_MAPPER
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("com.limanyik.family.common.bean.base.BaseEntity");
        strategy.setSuperMapperClass("com.limanyik.family.common.bean.base.BaseMapper");
        strategy.setSuperServiceClass("com.limanyik.family.common.bean.base.BaseService");
        strategy.setSuperServiceImplClass("com.limanyik.family.common.bean.base.BaseServiceImpl");
        strategy.setSuperControllerClass("com.limanyik.family.common.bean.base.BaseController");
        //生成字段常量
        strategy.setEntityColumnConstant(true);
        //生成字段注解
        strategy.setEntityTableFieldAnnotationEnable(true);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(TABLE_NAMES);
        // 自定义实体，公共字段
        strategy.setSuperEntityColumns(new String[]{"id", "create_time", "update_time", "creator_id", "updater_id", "creator_name", "updater_name", "delete_status","version"
        });
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(TABLE_PREFIX + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

